<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j con-box page-uc-balance">
    <div class="uc-nav">
      <div class="nav-box">
        <div
          :class="['nav-item', sts === 0 ? 'active' : '']"
          @click="changeTab(0)"
        >
          <span class="text">{{ $t('myBalance.myBalance') }}</span>
          <i class="line" />
        </div>
        <div
          :class="['nav-item', sts === 1 ? 'active' : '']"
          @click="changeTab(1)"
        >
          <span class="text">{{ $t('myBalance.balanceTopUp') }}</span>
          <i class="line" />
        </div>
      </div>
    </div>
    <!-- 我的余额 -->
    <div
      v-if="sts === 0"
      class="balance-detail"
    >
      <!-- 当前可用余额 -->
      <div class="uc-serach">
        <div class="left">
          <div class="current-balance">
            {{ $t('myBalance.currentAvailableBalance') }}：
            <span class="number">{{ currentBalance }}{{ $t('myBalance.yuan') }}</span>
          </div>

          <div class="right">
            <a
              class="search"
              @click="balanceTopUp"
            >{{ $t('myBalance.balanceTopUp') }}</a>
          </div>
        </div>
      </div>
      <!-- 当前可用余额 -->

      <table
        style="border-spacing: 0"
        class="box"
      >
        <tbody>
          <tr class="box-tit">
            <th>{{ $t('myBalance.sourceUse') }}</th>
            <th style="width: 400px;">
              {{ $t('myBalance.balanceChange') }}
            </th>
            <th>{{ $t('myBalance.Time') }}</th>
          </tr>
          <tr
            v-for="(item, index) in scoreDetList"
            :key="index"
            class="box-hd"
          >
            <td>
              <div class="text">
                <!-- 1:充值 2:赠送 3:支付 4:退款 5平台手动修改 6.充值会员 -->
                <div class="text">
                  <span v-if="item.type === 1">
                    {{ $t('myBalance.balanceTopUp') }}
                  </span>
                  <span v-if="item.type === 2">
                    {{ $t('myBalance.giftAmount') }}
                  </span>
                  <span v-if="item.type === 3">
                    {{ $t('myBalance.shopping') }}
                  </span>
                  <span v-if="item.type === 4">
                    {{ $t('myBalance.orderRefunds') }}
                  </span>
                  <span v-if="item.type === 5">
                    {{ $t('myBalance.platformManualModification') }}
                  </span>
                  <span v-if="item.type === 6">
                    {{ $t('myBalance.topUpMembers') }}
                  </span>
                  <span
                    v-if="item.orderNumbers"
                    class="order-number"
                  >
                    {{ $t('myBalance.orderNumber') }}:
                    <div class="order-number-con">
                      <span
                        v-for="(orderNumberItem, orderNumberIndex) in item.orderNumberList"
                        :key="orderNumberIndex"
                        class="order-number-item"
                      >{{ orderNumberItem }}</span>
                    </div>
                  </span>
                </div>
              </div>
            </td>
            <td>
              <div
                v-if="item.ioType === 0"
                class="balance-change"
              >
                -{{ item.changeBalance }}
              </div>
              <div
                v-if="item.ioType === 1"
                class="balance-change add"
              >
                +{{ item.changeBalance }}
              </div>
            </td>
            <td>
              <div class="time">
                {{ item.createTime }}
              </div>
            </td>
          </tr>
          <tr v-if="!scoreDetList.length">
            <td colspan="3">
              {{ $t('shopInfo.noData') }}
            </td>
          </tr>
        </tbody>
      </table>
      <!-- 页码 -->
      <pagination
        v-model="scoreCurrent"
        :pages="scorePages"
        @change-page="getScoreDet"
      />
      <!-- /页码 -->
    </div>
    <!-- /我的余额 -->

    <!-- 余额充值 -->
    <div
      v-if="sts === 1"
      class="goods-list balance-exchange"
    >
      <div class="topup">
        <div>
          <div class="topup-con">
            <div class="pay-box">
              <div class="pay-info">
                <div class="item">
                  <div class="tit">
                    {{ title }}
                  </div>
                </div>
                <div
                  v-if="tip"
                  class="itemTip"
                >
                  {{ tip }}
                </div>
              </div>
            </div>
            <div class="section-topup">
              <div
                v-if="topUpList.length"
                class="items sku-text"
              >
                <span class="tit">{{ $t('myBalance.topUpAmount') }}</span>
                <div class="con">
                  <span
                    v-for="(item, index) in topUpList"
                    :key="index"
                    class="item"
                    :class="[rechargeId === item.balanceId ? 'active' : '']"
                    @click="selectAmount(item)"
                  >{{ item.rechargeAmount }}{{ $t('myBalance.yuan') }}</span>
                </div>
              </div>

              <div class="items sku-text">
                <span class="tit">{{ $t('myBalance.customAmounts') }}({{ $t('myBalance.yuan') }})</span>
                <div class="con">
                  <input
                    v-model="customAmounts"
                    type="text"
                    class="text"
                    :placeholder="$t('myBalance.upToTopUp')"
                    @input="changeNum"
                    @focus="changeNum"
                  >
                  <span class="unit">{{ $t('myBalance.yuan') }}</span>
                </div>
              </div>
              <div class="items sku-text">
                <span class="tit">{{ $t('myBalance.currentBalance') }}({{ $t('myBalance.yuan') }})</span>
                <div class="con">
                  <span class="number">{{ currentBalance }}</span>
                </div>
              </div>

              <div class="items sku-text">
                <span class="tit">{{ $t('myBalance.selectPaymentMethod') }}</span>
                <div class="con">
                  <div
                    v-if="paySwitchInfo.aliPaySwitch"
                    class="itemPay"
                    :class="{active: payType === PayTypeConstant.ALIPAY}"
                    @click="payType = PayTypeConstant.ALIPAY"
                  >
                    <img
                      src="@/assets/images/payment-aliPay.png"
                      alt
                    >
                    <span class="payment-text">{{ $t('payment.aliPay') }}</span>
                    <div class="pay-html" />
                  </div>
                  <div
                    v-if="paySwitchInfo.wxPaySwitch"
                    class="itemPay"
                    :class="{active: payType === PayTypeConstant.WECHATPAY_SWEEP_CODE}"
                    @click="payType = PayTypeConstant.WECHATPAY_SWEEP_CODE"
                  >
                    <img
                      src="@/assets/images/payment-wechatPay.png"
                      alt
                    >
                    <span class="payment-text">{{ $t('payment.wechatPay') }}</span>
                  </div>
                  <div
                    v-if="paySettlementType !== 1 && paySwitchInfo.payPalSwitch"
                    class="itemPay paypal"
                    :class="{active: payType === PayTypeConstant.PAYPAL}"
                    @click="payType = PayTypeConstant.PAYPAL"
                  >
                    <img
                      class="paypal-logo"
                      src="@/assets/images/paypal.png"
                      alt
                    >
                    <img
                      class="paypal-text"
                      src="@/assets/images/paypal-text.png"
                      alt
                    >
                  </div>
                </div>
              </div>

              <a
                href="javascript:void(0)"
                :class="[isCanTopUp ? '' : 'no-pay', 'btn']"
                @click="toTopUp"
              >{{ $t('myBalance.topUpNow') }}</a>
            </div>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      v-model="dialogTableVisible"
      title=""
      width="60%"
      :before-close="beforeClose"
    >
      <weixin-pay-code
        v-if="weixinCodeUrl !== '' && dialogTableVisible"
        ref="weixinCodRef"
        :weixin-code-url="weixinCodeUrl"
      />
      <!-- 支付宝支付 -->
      <alipay-code
        v-if="alipayCodeUrl !== '' && dialogTableVisible"
        ref="alinpayCodeRef"
        :alipay-code-url="alipayCodeUrl"
      />
    </el-dialog>
    <!-- /余额充值 -->
  </div>
</template>

<script setup>
import { PayType } from '@/utils/constant.js'
import { checkPayWay } from '@/utils/index'
import { ElLoading, ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

const isCanTopUp = ref(true) // 是否能充值

const currentBalance = ref(0) // 当前可用余额
const sts = ref(route.query.sts || 0) // tab状态
const paySettlementType = ref(0)
const alipayCodeUrl = ref('')
let bizOrderNo = ''
let allinpayMemberInfo = null
onMounted(() => {
  // 设置网页标题
  document.title = $t('myBalance.myBalance')
  // 中心信息
  http.get('/p/userBalance/getBalanceInfo').then(({ data }) => {
    currentBalance.value = data
  })
  paySettlementType.value = localStorage.getItem('bbcPaySettlementType') ? JSON.parse(localStorage.getItem('bbcPaySettlementType')).paySettlementType : 0

  // 获取
  // getScoreDet()
  setDefaultPayType()
  // 切换tab
  changeTab(sts.value)

  getList()
  if (paySettlementType.value === 1) {
    getAllinpayMember()
  }
})

const scoreDetList = ref([]) // 列表
const scorePages = ref(1) // 总页数
const scoreCurrent = ref(1)
const scoreSize = 10
// 获取
const getScoreDet = () => {
  const params = {
    current: scoreCurrent.value,
    size: scoreSize.value
  }
  http.get('/p/userBalanceLog/log', { params }).then(({ data }) => {
    data.records.forEach(el => {
      if (el.orderNumbers) {
        el.orderNumberList = el.orderNumbers.split(',')
      }
    })
    scoreDetList.value = data.records
    scorePages.value = data.pages
    scoreCurrent.value = data.current
  })
}

const paySwitchInfo = ref('')
const payType = ref(PayType.ALIPAY) // 支付类型，默认支付宝
/**
 * 设置默认支付类型
 */
const setDefaultPayType = () => {
  http.get('/sys/config/info/getSysPaySwitch').then(({ data }) => {
    paySwitchInfo.value = data
    if (paySwitchInfo.value.aliPaySwitch) {
      return
    }
    if (paySwitchInfo.value.wxPaySwitch) {
      payType.value = PayType.WECHATPAY_SWEEP_CODE
      return
    }
    if (paySwitchInfo.value.payPalSwitch) {
      payType.value = PayType.PAYPAL
    }
  })
}

const topUpList = ref([]) // 套餐
// 获取充值数据列表
const getList = () => {
  http.get('/p/userBalance/getList').then(({ data }) => {
    topUpList.value = data
    if (topUpList.value.length === 0) {
      changeNum()
      return
    }
    selectAmount(data[0])
  })
}

const rechargeId = ref('')
const title = ref('')
const tip = ref('')
const customAmounts = ref('') // 自定义金额
// 选择充值金额
const selectAmount = (item) => {
  rechargeId.value = item.balanceId
  title.value = item.balanceTitle
  let tipPar = ''
  const head = $t('myBalance.rechargeoffer')
  if (item.presAmount && paySettlementType.value !== 1) {
    tipPar += $t('myBalance.give') + item.presAmount + $t('myBalance.yuan') + $t('myBalance.comma')
  }
  if (item.presGrowth) {
    tipPar += $t('myBalance.give') + item.presGrowth + $t('myBalance.growthValue') + $t('myBalance.comma')
  }
  if (item.presScore) {
    tipPar += $t('myBalance.give') + item.presScore + $t('myBalance.integral') + $t('myBalance.comma')
  }
  if (item.couponList !== null) {
    if (item.couponList.length > 0) {
      tipPar += $t('myBalance.give') + item.couponList.length + $t('myBalance.coupons')
      tipPar += '【'
      let couponStr = ''
      item.couponList.forEach((coupon, index) => {
        couponStr += coupon.couponName + (index < item.couponList.length - 1 ? '、' : '')
      })
      tipPar += couponStr + '】'
    }
  }
  if (tipPar !== '') {
    tipPar = head + tipPar
  }
  tip.value = tipPar
  customAmounts.value = ''
}

// 切换tab
const changeTab = (stsPar) => {
  if (getTip(sts)) {
    return
  }
  sts.value = stsPar // 0 1余额充值
  if (sts.value === 0) {
    // 获取
    getScoreDet()
  }
}

// 余额充值
const balanceTopUp = () => {
  if (getTip(1)) {
    return
  }
  sts.value = 1
}

const changeNum = () => {
  rechargeId.value = -1
  title.value = $t('myBalance.customAmounts')
  tip.value = $t('myBalance.upToTopUp')
  const customAmountsPar = customAmounts.value
  customAmounts.value = checkInput(customAmountsPar)
  if (Number.parseFloat(customAmounts.value) > 100000) {
    customAmounts.value = 100000
  }
}

/**
 * input输入框只允许输入正数和小数(保留小数点后两位)
 */
const checkInput = (num) => {
  if (num) {
    let tmpVal = num.replace(/[^\d^\\.]/g, '')
    const reg = /^(0|([1-9]\d*))(\.\d{1,2})?$/ // 最多允许后输入两位小数
    if (!reg.test(tmpVal)) {
      tmpVal = tmpVal + ''
      tmpVal = tmpVal.substring(0, tmpVal.indexOf('.') + 3)
      const n = (tmpVal.split('.')).length - 1
      if (n > 1) {
        tmpVal = tmpVal.substring(0, tmpVal.indexOf('.'))
      }
    }
    return tmpVal
  } else {
    return ''
  }
}

const payHtml = ref('') // 支付宝页面
const PayTypeConstant = ref(PayType) // 支付类型常量
const weixinCodeUrl = ref('') // 微信二维码数据
const dialogTableVisible = ref(false)
// 立即充值
const toTopUp = () => {
  if (rechargeId.value === '') {
    ElMessage({
      message: $t('myBalance.amountNull'),
      type: 'warning',
      duration: 1000
    })
    return
  }
  if (rechargeId.value === -1 && (customAmounts.value === '' || customAmounts.value <= 0)) {
    ElMessage({
      message: $t('myBalance.amountNull'),
      type: 'warning',
      duration: 1000
    })
    return
  }
  if (!checkPayWay(paySwitchInfo.value)) return
  const {
    protocol,
    host
  } = window.location
  const redirectUrl = `${protocol}//${host}` + '/user-center/uc-balance'
  const rechargeBalanceData = {
    payType: payType.value,
    returnUrl: paySettlementType.value === 1 ? undefined : redirectUrl,
    id: rechargeId.value,
    customRechargeAmount: Number.parseFloat(customAmounts.value),
    scene: ''
  }
  http.post('/p/balance/pay', rechargeBalanceData).then(({ data }) => {
    if (paySettlementType.value === 1) {
      // 通联支付下，微信与支付宝支付都通过二维码扫码支付
      bizOrderNo = data.bizOrderNo
      if (payType === PayType.WECHATPAY_SWEEP_CODE) {
        dialogTableVisible.value = true
        // 清空url地址防止出现两个
        alipayCodeUrl.value = ''
        weixinCodeUrl.value = data.payInfo
        isAllinPaySuccess()
      } else if (payType === PayType.ALIPAY) {
        dialogTableVisible.value = true
        weixinCodeUrl.value = ''
        alipayCodeUrl.value = data.payInfo
        isAllinPaySuccess()
      }
      return
    }
    if (payType.value === PayType.ALIPAY) {
      payHtml.value = data

      const elementCreate = document.createElement('div')
      elementCreate.innerHTML = payHtml.value
      nextTick(() => {
        document.querySelector('.pay-html')?.appendChild(elementCreate)
        document.forms[0].submit()
      })
    }
    if (payType.value === PayType.WECHATPAY_SWEEP_CODE) {
      weixinCodeUrl.value = data
      dialogTableVisible.value = true
      isPay()
    }
    if (payType.value === PayType.PAYPAL) {
      // PayPal部分
      const loading = ElLoading.service({
        lock: true,
        text: $t('loading'),
        background: 'rgba(255, 255, 255, 0.8)'
      })
      window.location.href = data
      setTimeout(() => {
        loading.close()
      }, 2000)
    }
  }).catch(() => {})
}

let checkIsPay = null
// 判断是否支付
const isPay = () => {
  checkIsPay = window.setInterval(() => {
    if (!dialogTableVisible.value) {
      window.clearInterval(checkIsPay)
    }
    http.get('/p/balance/isPay').then(({ data }) => {
      if (data === 1) {
        window.clearInterval(checkIsPay)
        router.go(0)
      }
    })
  }, 3000)
}

const beforeClose = (done) => {
  dialogTableVisible.value = false
  done()
}
// 获取通联支付用户信息
const getAllinpayMember = () => {
  http.get('/p/userExtension/getInfo').then(({ data }) => {
    allinpayMemberInfo = data
  })
}
const getTip = (sts) => {
  if (paySettlementType.value === 1 && sts === 1) {
    if (!allinpayMemberInfo) {
      return true
    }
    let msg = ''
    if (!allinpayMemberInfo.allinpayRealNameSet) {
      msg += $t('allinpay.realNameTip1')
    }
    if (!allinpayMemberInfo.allinpayPhoneBind) {
      if (msg) {
        msg += $t('allinpay.bindPhone3')
      } else {
        msg += $t('allinpay.bindPhone')
      }
    }
    if (msg) {
      ElMessage({
        message: $t('allinpay.tip1') + msg + $t('allinpay.tip2'),
        type: 'error',
        duration: 1000
      })
      return true
    }
  }
}
// 判断是否支付成功（通联）
const isAllinPaySuccess = () => {
  checkIsPay = window.setInterval(() => {
    if (!dialogTableVisible.value) {
      window.clearInterval(checkIsPay)
    }
    http.get('/p/allinpay/order/getOrderStatus', {
      params: {
        bizOrderNo
      }
    }).then(({ data }) => {
      if (data.orderStatus === 4) {
        window.clearInterval(checkIsPay)
        router.go(0)
      }
    })
  }, 3000)
}

</script>

<style lang="scss" scoped>
@use "../common/scss/user-center";
</style>
<style lang="scss" scoped>
@use "index";
</style>
